
import java.util.Scanner;

public class Main {

    // 计算子数组之和的最大值的方法
    public static int maxSubArraySum(int[] nums) {
        // 当传入数组为空时，报错
        if (nums == null || nums.length == 0) 
            throw new IllegalArgumentException("数组不能为空");

        int currentMax = nums[0]; // 以当前元素结尾的最大子数组和
        int maxSum = nums[0];     // 全局最大子数组和

        // 从第二个元素开始遍历
        for (int i = 1; i < nums.length; i++) {
            // 决定是延续之前的子数组还是从当前元素重新开始
            currentMax = Math.max(nums[i], currentMax + nums[i]);
            // 更新全局最大值
            maxSum = Math.max(maxSum, currentMax);
        }

        return maxSum; 
    }

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            // 要求用户输入数组成员数量
            System.out.print("Please enter the number of array elements: ");
            int arrayNumber = scanner.nextInt();

            // 要求用户输入数组内容
            int[] array = new int[arrayNumber];
            System.out.print("Please enter its elements: ");
            for (int i = 0; i < arrayNumber; i++) {
                array[i] = scanner.nextInt();
            }

            // 输出数组的子数组之和的最大值
            System.out.println("The maximum sum of sub-arrays of this array is " + maxSubArraySum(array));
        }
    }
}
